'use strict'

import Vue from 'vue'
import axios from 'axios'
import Util from '../assets/js/util.js'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// let config = {
//   // baseURL: process.env.baseURL || process.env.apiUrl || ""
//   // timeout: 60 * 1000, // Timeout
//   // withCredentials: true, // Check cross-site Access-Control
// }

//const _axios = axios.create(config)

// Axios拦截器
axios.interceptors.request.use(
  // Do something before request is sent
  config => {
    config.timeout = 200000
    config.withCredentials = true
    if (config.headers['Content-Type'] === undefined) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
      // json -> form data
      config['transformRequest'] = [
        data => {
          return Util.jsonToString(data)
        }
      ]
    }
    return config
  },
  error => {
    if (Util.isEmpty(error.errorMessage)) {
      Object.assign(error, { errorMessage: '系统异常！' })
    }
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  // Do something with response data
  response => {
    return Object.assign({ success: true }, response)
  },
  error => {
    Object.assign(error, { errorMessage: '系统异常！' })
    return Promise.reject(error)
  }
)

Plugin.install = function(Vue) {
  Vue.axios = axios
  window.axios = axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return axios
      }
    },
    $axios: {
      get() {
        return axios
      }
    }
  })
}

Vue.use(Plugin)

export default Plugin
